package com.barradata.common.view

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import com.barradata.R
import kotlinx.android.synthetic.main.navigation_bar.view.*


/**
 * Created by WuNan-QF on 16/3/4.
 *
 * Refactored by WuNan on 2019-07-14 22:02
 */
class NavigationBar : RelativeLayout {

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        View.inflate(context, R.layout.navigation_bar, this)
        if (attrs != null) {
            val a = context.obtainStyledAttributes(attrs, R.styleable.NavigationBar)
            val barBackgroundDrawable = a.getDrawable(R.styleable.NavigationBar_bar_background)
            if (barBackgroundDrawable != null) {
                bar_layout.background = barBackgroundDrawable
            }
            setTitle(a.getString(R.styleable.NavigationBar_center_text))
            nav_left.text = a.getString(R.styleable.NavigationBar_left_text)
            setDrawable(nav_left, a.getResourceId(R.styleable.NavigationBar_left_drawable, -1))
            nav_left.setTextColor(a.getColor(R.styleable.NavigationBar_left_text_color, 0xfff))
            nav_left.visibility = if (a.getBoolean(R.styleable.NavigationBar_left_hide, false))
                View.GONE
            else
                View.VISIBLE
            nav_right1.text = a.getString(R.styleable.NavigationBar_right1_text)
            nav_right1.setTextColor(a.getColor(R.styleable.NavigationBar_right1_text_color, 0xfff))
            setDrawable(nav_right1, a.getResourceId(R.styleable.NavigationBar_right1_drawable, -1))
            nav_right2.text = a.getString(R.styleable.NavigationBar_right2_text)
            nav_right2.setTextColor(a.getColor(R.styleable.NavigationBar_right2_text_color, 0xfff))
            setDrawable(nav_right2, a.getResourceId(R.styleable.NavigationBar_right2_drawable, -1))
            a.recycle()
        }
    }

    fun setTitle(title: String?) {
        nav_center.text = title
    }

    fun setLeftDrawable(drawableId: Int) {
        setDrawable(nav_left, drawableId)
    }

    fun setRight1Drawable(drawableId: Int) {
        setDrawable(nav_right1, drawableId)
    }

    fun setRight2Drawable(drawableId: Int) {
        setDrawable(nav_right2, drawableId)
    }


    private fun setDrawable(v: TextView, drawableId: Int) {
        if (drawableId > 0) {
            val drawable = resources.getDrawable(drawableId)
            v.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null)
        }
    }
}